<template>
  <div>
    <el-dialog :title="isEdit ? '编辑部门' : '新增部门'" :visible="showDialog" :append-to-body="true" @close="close">
      <el-form ref="ruleForm" :model="form" :rules="rules">
        <el-form-item label="部门名称" label-width="150px" prop="name">
          <el-input v-model="form.name" placeholder="2-10个字符" />
        </el-form-item>
        <el-form-item label="部门编码" label-width="150px" prop="code">
          <el-input v-model="form.code" placeholder="2-10个字符" />
        </el-form-item>
        <el-form-item label="部门负责人" label-width="150px" prop="managerId">
          <el-select v-model="form.managerId" placeholder="请选择负责人" prop="region">
            <el-option v-for="item in managerList" :key="item.id" :label="item.username" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="活动形式" label-width="150px" prop="introduce">
          <el-input v-model="form.introduce" type="textarea" placeholder="1-100个字符" />
        </el-form-item>
        <el-form-item label-width="150px">
          <el-button type="primary" @click="submitForm">{{ isEdit ? '更新' : '新增' }}</el-button>
          <el-button @click="close">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { addDepartmentRequest, getUserSimpleRequest, getDepartmentDetailRequest, updateDepartmentRequest } from '@/api/department'
import { cloneDeep } from 'lodash'
export default {
  name: '',
  props: {
    showDialog: {
      type: Boolean
    },
    departmentList: {
      type: Array,
      default: () => {
        return
      }
    },
    currentId: {
      type: [Number, String],
      default: ''
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validatorName = (rule, value, callback) => {
      let res = cloneDeep(this.departmentList)
      if (this.isEdit) {
        res = res.filter(item => item.id !== this.currentId)
      }
      if (res.some(item => item.name === value)) {
        callback(new Error('部门名称重复'))
      } else {
        callback()
      }
    }
    const validatorCode = (rule, value, callback) => {
      let res = cloneDeep(this.departmentList)
      if (this.isEdit) {
        res = res.filter(item => item.id !== this.currentId)
      }

      if (res.some(item => item.code === value)) {
        callback(new Error('部门名称重复'))
      } else {
        callback()
      }
    }
    return {
      form: {
        code: '',
        introduce: '',
        managerId: '',
        name: '',
        pid: ''
      },
      managerList: [],
      rules: {
        name: [
          { required: true, message: '请填写部门名称', trigger: 'blur' },
          { min: 2, max: 10, message: '部门名称位数有误' },
          { 'validator': validatorName, trigger: ['blur', 'change'] }
        ],
        code: [
          { required: true, message: '请填写部门编码', trigger: 'blur' },
          { min: 2, max: 10, message: '部门编码位数有误' },
          { 'validator': validatorCode, trigger: ['blur', 'change'] }
        ],
        managerId: [
          { required: true, message: '请填写部门负责人', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '请填写活动形式', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    // 这里不需要写箭头函数
    isEdit(newVal, oldVal) {
      console.log(newVal, oldVal)
      if (newVal) {
        // 凡是看到this，就要小心thsi指向混乱问题
        this.getDepartmentDetail()
      }
    }
  },
  created() {
    this.getUserSimple()
  },
  methods: {
    close() {
      this.$emit('update:showDialog', false)
      this.$emit('update:is-edit', false)
      this.$refs.ruleForm.resetFields()
      this.form = this.$options.data().form
    },
    async getDepartmentDetail() {
      console.log('请求这里值有没有id：', this.currentId)
      const res = await getDepartmentDetailRequest(this.currentId)
      this.form = res.data
    },
    async getUserSimple() {
      const res = await getUserSimpleRequest()
      this.managerList = res.data
    },
    submitForm() {
      this.$refs.ruleForm.validate(async(valid) => {
        if (valid) {
          this.pid = this.currentId
          if (this.isEdit) {
            console.log(this.form)
            await updateDepartmentRequest(this.form)
          } else {
            await addDepartmentRequest({ ...this.form, pid: this.currentId })
          }

          this.close()
          this.$message({
            message: `${this.isEdit ? '编辑' : '添加'}部门成功`,
            type: 'success'
          })
          this.$emit('add-success')
        }
      })
    }
  }
}
</script>
